const mongoose = require("mongoose");

const PosOrderSchema = new mongoose.Schema(
  {
    warehouse: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Warehouse",
      required: true,
    },
    customer: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "CustomerData",
      required: true,
    },
    // Invoice details
    invoiceCode: {
      type: String,
      required: false,
    },
    invoiceCount: {
      type: Number,
      default: 0,
    },
    previousBalance: {
      type: Number,
      default: 0,
    },
    // New fields for enhancements
    couponCode: {
      type: String,
      default: "",
    },
    balanceDue: {
      type: Number,
      default: 0,
    },
    changeReturn: {
      type: Number,
      default: 0,
    },
    advanceUsed: {
      type: Number,
      default: 0,
    },
    // NEW: Account field to store the selected account (if provided)
    account: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Account", // make sure your Account model is named "Account"
      required: false,
    },
    // Order items array
    items: [
      {
        item: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Item",
          required: true,
        },
        quantity: { type: Number, required: true },
        price: { type: Number, required: true },
        discount: { type: Number, default: 0 },
        unit: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Unit",
          required: false,
        },
        tax: { type: mongoose.Schema.Types.ObjectId, ref: "Tax" },
        subtotal: { type: Number, required: true },
      },
    ],
    totalAmount: { type: Number, required: true },
    totalDiscount: { type: Number, default: 0 },
    payments: [
      {
        paymentType: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "PaymentType",
          required: true,
        },
        amount: { type: Number, required: true },
      },
    ],
    status: {
      type: String,
      enum: ["OnHold", "Pending", "Completed"],
      default: "Pending",
    },
    // Indicates whether the order is fully paid (balanceDue === 0)
    isPaid: {
      type: Boolean,
      default: false,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("PosOrder", PosOrderSchema);
